package gov.pbc.nn.core.bdf.authoritydelegation.view.select;

import gov.pbc.nn.core.bdf.authoritydelegation.AuthoritydelegationHibernateDao;
import gov.pbc.nn.core.bdf.authoritydelegation.service.IAuthoritydelegationService;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.model.Role;
import com.bstek.bdf2.core.service.impl.DefaultRoleService;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

@Component("bdf2.roleSelectAd")
public class RoleSelect extends AuthoritydelegationHibernateDao {

	@SuppressWarnings("unchecked")
	@DataProvider
	public void loadRoles(Page<Role> page, Criteria criteria) throws Exception {
		IUser user = ContextHolder.getLoginUser();
		if (user == null) {
			throw new RuntimeException("Please login first");
		}
		String companyId = user.getCompanyId();
		if (StringUtils.isNotEmpty(getFixedCompanyId())) {
			companyId = getFixedCompanyId();
		}
		if (user.isAdministrator()) {
			this.loadAllRoles(page, criteria);
		} else {
			IAuthoritydelegationService ad = ContextHolder.getBean(IAuthoritydelegationService.BEAN_ID_);
//			Page<Role> page1 = new Page<Role>(page.getPageSize(), page.getPageNo());
			ad.findControllableRoles(page, user.getUsername(), criteria);
//			Collection<Role> uList = page1.getEntities();
//			if (uList.size() > 0) {
//				Collection<?> userList = page1.getEntities();
//				page.setEntities((Collection<Role>) userList);
//				page.setEntityCount(page1.getEntityCount());
//			}
		}
	}

	private void loadAllRoles(Page<Role> page, Criteria criteria) {
		DetachedCriteria dc = this.buildDetachedCriteria(criteria, Role.class);
		this.pagingQuery(page, dc);
//		
//		String sql = "SELECT R.ID_,R.COMPANY_ID_,R.ENABLED_,R.DESC_,R.NAME_ FROM BDF2_ROLE R";
//		DefaultRoleService roleService = ContextHolder.getApplicationContext().getBean(DefaultRoleService.class);
//		
//		return roleService.getJdbcTemplate().query(sql, new RowMapper<Role>() {
//
//			public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
//				Role role = new Role();
//				role.setId(rs.getString(1));
//				role.setCompanyId(rs.getString(2));
//				if (rs.getObject("ENABLED_") != null) {
//					role.setEnabled(rs.getBoolean(3));
//				}
//				role.setDesc(rs.getString(4));
//				role.setName(rs.getString(5));
//				return role;
//			}
//
//		});
	}
}
